package com.example.gobang.api;

import com.example.gobang.game.MatchRequest;
import com.example.gobang.game.MatchResponse;
import com.example.gobang.game.Matcher;
import com.example.gobang.game.OnlineUserManager;
import com.example.gobang.model.User;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

/**
 * author: hyacinth
 * 处理 websocket 请求
 * Date: 2023/5/25
 */
@Component
public class MatchAPI extends TextWebSocketHandler {
    @Autowired
    private OnlineUserManager onlineUserManager;

    @Autowired
    private Matcher matcher;
    private final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 玩家上线
     * @param session
     * @throws Exception
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        // 1.获取用户信息
        User user = null;
        try {
            user = (User) session.getAttributes().get("user");
            // 2.判断用户是否已经登陆过了
            WebSocketSession tmpSession = onlineUserManager.getSessionFromGameHall(user.getUserId());
            if (tmpSession != null){
                // 登录过了
                MatchResponse response = new MatchResponse();
                response.setOk(true);
                response.setReason("当前禁止多开!");
                response.setMessage("repeatConnection");
                session.sendMessage(new TextMessage(objectMapper.writeValueAsString(response)));

                return;
            }
            onlineUserManager.enterGameHall(user.getUserId(),session);
            System.out.println("玩家"+user.getUsername()+"进入游戏大厅!");
        } catch (NullPointerException e) {
            e.printStackTrace();

            MatchResponse matchResponse = new MatchResponse();
            matchResponse.setOk(false);
            matchResponse.setReason("您尚未登录!请登录!");
            session.sendMessage(new TextMessage(objectMapper.writeValueAsString(matchResponse)));
        }

    }

    /**
     * 处理 开始匹配和停止匹配请求
     * @param session
     * @param message
     * @throws Exception
     */
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        // 实现处理 开始匹配和停止匹配的请求
        User user = (User) session.getAttributes().get("user");
        // 获取客户端给服务器发送的数据
        String payload = message.getPayload();
        MatchRequest request = objectMapper.readValue(payload, MatchRequest.class);
        MatchResponse response = new MatchResponse();
        if (request.getMessage().equals("startMatch")){
            // 开始匹配
            matcher.add(user);
            response.setOk(true);
            response.setMessage("startMatch");
        } else if (request.getMessage().equals("stopMatch")) {
            // 停止匹配
            matcher.remove(user);
            response.setOk(true);
            response.setMessage("stopMatch");
        }else{
            // 非法请求
            response.setOk(false);
            response.setReason("非法的匹配请求");
        }
        session.sendMessage(new TextMessage(objectMapper.writeValueAsString(response)));
    }

    /**
     * 玩家下线
     * @param session
     * @param exception
     * @throws Exception
     */
    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        User user = null;
        try {
            user = (User) session.getAttributes().get("user");
            WebSocketSession tmpSession = onlineUserManager.getSessionFromGameHall(user.getUserId());
            if (tmpSession == session){
                onlineUserManager.exitGameHall(user.getUserId());
            }
            // 在匹配中 玩家退出
            matcher.remove(user);
        } catch (NullPointerException e) {
            System.out.println("[handleTransportError]: 当前用户未登录!");

        }
    }

    /**
     * 玩家下线
     * @param session
     * @param status
     * @throws Exception
     */
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        User user = null;
        try {
            user = (User) session.getAttributes().get("user");
            WebSocketSession tmpSession = onlineUserManager.getSessionFromGameHall(user.getUserId());
            if (tmpSession == session){
                onlineUserManager.exitGameHall(user.getUserId());
            }
            matcher.remove(user);
        } catch (NullPointerException e) {
            System.out.println("[afterConnectionClosed]: 当前用户未登陆!");
        }
    }
}
